import { useTableScroll } from '@/hooks/useTableScroll';
import {
  getWithdrawRecord,
  sendCaptcha,
  submitWithdraw,
} from '@/services/financial-center';
import { FormatNumber } from '@/utils/format';
import { accDiv, accMul } from '@/utils/math';
import { ActionType, ProColumns, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, Col, Form, Input, message, Row, Typography } from 'antd';
import { useEffect, useRef, useState } from 'react';
const { Text } = Typography;
let timer: any = null;

const ServiceWithdraw = () => {
  const [count] = useState(0);
  const tableScrollHeight = useTableScroll({}, count);
  const actionRef = useRef<ActionType>();
  const [disable, setDisable] = useState(false);
  const [countDown, setCountDown] = useState(60);
  const { initialState, refresh } = useModel('@@initialState');
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const columns: ProColumns<any>[] = [
    {
      title: '提现时间',
      dataIndex: 'createTime',
      width: 160,
    },
    {
      title: '流水号',
      dataIndex: 'bizNo',
      width: 180,
    },
    {
      title: '支付宝账号',
      dataIndex: 'alipayNickName',
      width: 160,
    },
    {
      title: '支付宝实名',
      dataIndex: 'realName',
      width: 160,
    },
    {
      title: '提现金额',
      dataIndex: 'transferMoney',
      width: 160,
      render: (_, record) => {
        return <div>{accDiv(record.transferMoney, 100)}</div>;
      },
    },
    {
      title: '提现状态',
      dataIndex: 'payStatus',
      width: 160,
      render: (_, record) => {
        const obj = {
          wait_pay: { text: '待提现' },
          payed: { text: '提现成功', type: 'success' },
          paying: { text: '转账中', type: 'warning' },
          pay_failed: { text: '提现失败', type: 'danger' },
        } as any;
        return (
          <Text {...obj[record.payStatus]}>{obj[record.payStatus].text}</Text>
        );
      },
    },
    {
      title: '完成时间',
      dataIndex: 'endTime',
      width: 160,
    },
  ];

  useEffect(() => {
    if (disable) {
      timer = setInterval(() => {
        setCountDown((countDown: number) => {
          if (countDown === 1) {
            setDisable(false);
            clearInterval(timer);
            return 60;
          }
          return countDown - 1;
        });
      }, 1000);
    }
  }, [disable]);

  const handleSubmit = async (values: any) => {
    setLoading(true);
    try {
      const res = (await submitWithdraw({
        ...values,
        amount: accMul(values.amount, 100).toFixed(0),
      })) as any;
      if (res.success) {
        message.success('提现成功');
        actionRef.current?.reload();
        form.resetFields();
        refresh();
      } else {
        message.error('提现失败');
      }
    } catch (error) {
    } finally {
      setLoading(false);
    }
  };

  return (
    <div>
      <div className="bg-white mb-6 p-4 rounded-lg">
        <div className="border inline-block py-2 px-4">
          服务费账户余额：¥
          {FormatNumber(accDiv(initialState?.currentUser.moneyLeft, 100))}
        </div>
        <Form
          layout="vertical"
          className="mt-4"
          form={form}
          onFinish={handleSubmit}
        >
          <Row gutter={24}>
            <Col span={5}>
              <Form.Item
                rules={[
                  { required: true, message: '请输入收款人姓名/收款企业名' },
                ]}
                label="收款人姓名/收款企业名"
                name={'realName'}
              >
                <Input placeholder="请输入收款人姓名/收款企业名" />
              </Form.Item>
            </Col>
            <Col span={7}>
              <Form.Item
                rules={[
                  {
                    required: true,
                    message: '提现收款账号（仅支持实名的支付宝账号）',
                  },
                ]}
                label="提现收款账号（仅支持实名的支付宝账号）"
                name={'alipayNickName'}
              >
                <Input placeholder="请输入提现收款账号" />
              </Form.Item>
            </Col>
          </Row>
          <Row align={'middle'}>
            <Col span={4}>
              <Form.Item
                rules={[{ required: true, message: '请输入提现金额' }]}
                label="提现金额"
                name={'amount'}
              >
                <Input addonAfter="元" placeholder="请输入提现金额" />
              </Form.Item>
            </Col>
            <Col
              className="ml-3 mt-2 text-[#00bdff] cursor-pointer"
              onClick={() => {
                form.setFieldValue(
                  'amount',
                  accDiv(initialState?.currentUser.moneyLeft, 100),
                );
              }}
            >
              全部余额
            </Col>
          </Row>
          <Row align={'middle'}>
            <Col>
              <Form.Item
                rules={[{ required: true, message: '请输入短信验证码' }]}
                label="短信验证码"
                name={'checkCode'}
              >
                <Input placeholder="请输入短信验证码" />
              </Form.Item>
            </Col>
            <Col className="mt-1 ml-4">
              <Button
                disabled={disable}
                onClick={async () => {
                  try {
                    const res = (await sendCaptcha()) as any;
                    if (res.success) {
                      setDisable(true);
                      message.success('发送成功');
                    } else {
                      message.error('发送验证码失败');
                    }
                  } catch (error) {
                    message.error('发送验证码失败');
                  }
                }}
              >
                {disable ? `${countDown}秒后重新发送` : '发送验证码'}
              </Button>
            </Col>
          </Row>
          <Row>
            <Col>
              <Form.Item>
                <Button htmlType="submit" loading={loading} type="primary">
                  确认提现
                </Button>
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </div>
      <ProTable
        scroll={{ y: tableScrollHeight, x: 200 }}
        rowKey="id"
        search={false}
        columns={columns}
        pagination={{
          defaultPageSize: 20,
          showQuickJumper: true,
          showSizeChanger: true,
        }}
        request={async (params: any) => {
          const res = (await getWithdrawRecord({
            pageNo: params.current - 1,
            pageSize: params.pageSize,
          })) as any;
          if (res.success) {
            return {
              data: res.data,
              total: res.count,
              success: true,
            };
          } else {
            message.error(res.resultMessage);
            return { data: [] };
          }
        }}
        actionRef={actionRef}
        cardBordered
        columnsState={{
          defaultValue: {
            option: { fixed: 'right', disable: true },
          },
        }}
      />
    </div>
  );
};

export default ServiceWithdraw;
